package com.wang.project.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.project.common.DeleteRequest;
import com.wang.project.common.ErrorCode;
import com.wang.project.constant.CommonConstant;
import com.wang.project.constant.UserConstant;
import com.wang.project.email.EmailSendCodeHandel;
import com.wang.project.exception.BusinessException;
import com.wang.project.mapper.UserMapper;
import com.wang.project.model.dto.user.*;
import com.wang.project.model.entity.User;
import com.wang.project.model.entity.UserKey;
import com.wang.project.model.file.FileQueryUrlParam;
import com.wang.project.model.file.FileUploadParam;
import com.wang.project.model.vo.UserVO;
import com.wang.project.service.FileService;
import com.wang.project.service.UserKeyService;
import com.wang.project.service.UserService;
import com.wang.project.utils.CommonUtils;
import com.wang.project.utils.FileUtils;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 用户服务实现类
 *
 * @author yupi
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserKeyService userKeyService;

    @Resource
    private EmailSendCodeHandel emailSendCodeHandel;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private FileService fileService;


    /**
     * 用户注册
     *
     * @return
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        log.info("UserServiceImpl userRegister UserRegisterRequest: " + JSONUtil.toJsonStr(userRegisterRequest));
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((CommonConstant.SALT + userPassword).getBytes());

            // 分配 ak sk
            String accessKey = DigestUtil.md5Hex(CommonConstant.SALT + userAccount + RandomUtil.randomNumbers(4));
            String secretKey = DigestUtil.md5Hex(CommonConstant.SALT + userAccount + RandomUtil.randomNumbers(8));

            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setAccessKey(accessKey);
            user.setSecretKey(secretKey);
            user.setLeftRefreshKeyTime(UserConstant.REFRESHKEYTIME);
            user.setUserRole(UserConstant.DEFAULT_ROLE); //默认为普通用户
            user.setUserName(RandomUtil.randomString(10));//随机名字
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }

            //将ak sk保存在用户key表中
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userAccount", userAccount);
            userQueryWrapper.eq("userPassword", encryptPassword);
            User resultUser = this.getOne(userQueryWrapper);
            UserKey userKey = new UserKey();
            userKey.setUser_id(resultUser.getId());
            userKey.setAccessKey(accessKey);
            userKey.setSecretKey(secretKey);
            boolean saveUserKeyResult = userKeyService.save(userKey);
            if (!saveUserKeyResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "保存ak sk错误，手动刷新");
            }
            return user.getId();
        }
    }

    /**
     * 用户登录
     *
     * @param request
     * @return
     */
    @Override
    public User userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("UserServiceImpl userLogin userLoginRequest: " + JSONUtil.toJsonStr(userLoginRequest));
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((CommonConstant.SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return user;
    }

    /**
     * 用户邮箱登录
     *
     * @param userEmailLoginRequest
     * @param request
     * @return
     */
    @Override
    public User userEmailLogin(UserEmailLoginRequest userEmailLoginRequest, HttpServletRequest request) {
        String email = userEmailLoginRequest.getEmail();
        String code = userEmailLoginRequest.getVerificationCode();
        log.info("UserServiceImpl userEmailLogin login email: {} ,code: {} ", email, code);
        if (!CommonUtils.isValidEmail(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        //判断邮箱用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = this.getOne(userQueryWrapper);
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱不存在");
        }
        log.info("UserServiceImpl userEmailLogin login user: {}", JSONUtil.toJsonStr(user));
        //判断验证码是否正确
        String redisCode = redisTemplate.opsForValue().get("email:" + email);
        if (redisCode.isEmpty() || !redisCode.equals(code)) {
            log.info("UserServiceImpl userEmailLogin redisCode: {}", redisCode);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        //记录用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return user;
    }


    /**
     * 获取当前登录用户
     * <p>
     * 登录的用户id会存在session中，在这拿到session中的id，
     * 根据id去查找这个用户，然后返回这个用户
     * 最后返回的用户就是当前的登录的用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        String fileName = currentUser.getUserAvatar(); //头像文件名
        if (!(fileName == null || StrUtil.hasEmpty(fileName))) {
            log.info("UserServiceImpl getLoginUser fileName: {}", fileName);
            String userAvatarUrl = this.getUserAvatarUrl(currentUser);
            log.info("UserServiceImpl getLoginUser userAvatarUrl: {}", userAvatarUrl);
            //设置在线地址
            currentUser.setUserAvatar(userAvatarUrl);
        }
        log.info("UserServiceImpl getLoginUser loginUser:{}", JSONUtil.toJsonStr(currentUser));
        return currentUser;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && UserConstant.ADMIN_ROLE.equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取所有用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @Override
    public List<UserVO> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        User userQuery = new User();
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        List<User> userList = this.list(queryWrapper);
        List<UserVO> userVOList = userList.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return userVOList;
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @Override
    public Page<UserVO> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        long size = 10;
        long current = 1;
        User userQuery = new User();
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
            current = userQueryRequest.getCurrent();
            size = userQueryRequest.getPageSize();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        Page<User> userPage = this.page(new Page<>(current, size), queryWrapper);
        Page<UserVO> userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    /**
     * 更新用户信息
     *
     * @param file              用户头像
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @Override
    public Boolean updateUser(MultipartFile file, UserUpdateRequest userUpdateRequest, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (userUpdateRequest == null || file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);

        //上传用户头像到minio
        User loginUser = this.getLoginUser(request);
        FileUploadParam fileUploadParam = new FileUploadParam();
        fileUploadParam.setType(userUpdateRequest.getType());
        fileUploadParam.setRegion(userUpdateRequest.getRegion());
        log.info("UserServiceImpl updateUser fileUploadParam:{}", JSONUtil.toJsonStr(fileUploadParam));
        try {
            fileService.uploadFile(file, fileUploadParam, loginUser);
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        }

        //获取当前用户上传的头像的地址
        FileQueryUrlParam fileQueryUrlParam = new FileQueryUrlParam();
        BeanUtils.copyProperties(fileUploadParam, fileQueryUrlParam);
        fileQueryUrlParam.setOriginalFilename(file.getOriginalFilename());
        String objectURL = fileService.getObjectURL(fileQueryUrlParam, loginUser);
        log.info("UserServiceImpl updateUser userAvatarUrl:{}", objectURL);
        //将图片的文件名保存到数据库中，每次获取用户头像地址的时候用文件名去查minio的在线地址，这样不需要考虑minio在线地址的过期问题
        String fileName = FileUtils.getMinioUploadFileName(fileUploadParam, user) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        user.setUserAvatar(fileName);
        return this.updateById(user);
    }

    /**
     * 邮箱登录 获取邮箱验证码
     *
     * @param userEmailLoginRequest
     * @return
     */
    @Override
    public String getEmailVerificationCode(UserEmailLoginRequest userEmailLoginRequest) {
        String code = CommonUtils.getVerityCode();// 随机六位数字验证码
        String email = userEmailLoginRequest.getEmail();
        log.info("UserServiceImpl getEmailVerificationCode email:{},code:{}", email, code);
        //发送验证给邮箱
        emailSendCodeHandel.sendCode(code, email);
        //保存到redis中 过期时间为两分钟 key为邮箱名，value为验证码code
        redisTemplate.opsForValue().set("email:" + userEmailLoginRequest.getEmail(), code, 2, TimeUnit.MINUTES);
        return "放送成功";
    }

    /**
     * 根据id获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @Override
    public UserVO getUserById(int id, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        UserVO userVO = new UserVO();
        //获取到的在线地址设置到UserVO上
        User user = this.getById(id);
        BeanUtils.copyProperties(user, userVO);
        String fileName = user.getUserAvatar();
        if (!(fileName == null || StrUtil.hasEmpty(fileName))) {
            log.info("UserServiceImpl getUserById fileName: {}" + fileName);
            String userAvatarUrl = this.getUserAvatarUrl(user);
            //设置在线地址
            userVO.setUserAvatar(userAvatarUrl);
        }
        return new UserVO();
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @Override
    public Boolean deleteUser(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = this.getLoginUser(request);
        String userAvatarUrl = loginUser.getUserAvatar();

        //删除minio头像文件
        if ((userAvatarUrl == null || StrUtil.hasEmpty(userAvatarUrl))) {
            String fileNameByUrl = FileUtils.getFileNameByUrl(userAvatarUrl);
            fileService.removeUserAvatar(fileNameByUrl);
        }
        //删除用户信息
        return this.removeById(deleteRequest.getId());
    }


    /**
     * 封装获取用户头像在线地址的通用方法
     *
     * @return
     */
    public String getUserAvatarUrl(User user) {
        FileQueryUrlParam fileQueryUrlParam = new FileQueryUrlParam();
        fileQueryUrlParam.setType("user");
        fileQueryUrlParam.setRegion("avatar");
        String userAvatarUrl = fileService.getUserAvatarUrl(fileQueryUrlParam, user);
        log.info("UserServiceImpl getLoginUser userAvatarUrl: {}", userAvatarUrl);
        return userAvatarUrl;
    }
}




